// 声明文件中的 libNames 值 必须替换掉，否则发布成npm包以后就读取不了了 
// 注意这个程序主要是为了处理声明文件的，不是处理js文件本身的。js文件中 @/xxx 都会被翻译成 ../xxx，但是声明文件不会被翻译为相对路径，使用时会导致路径报错
import fs from 'fs';
import path from 'path';
import yargs from 'yargs';

const libNames = ["CzmObjects", "ESCesiumViewer"];
const sdkName = 'earthsdk2-cesium';


/**
 * 文件遍历方法
 * @param fileDir 需要遍历的文件路径
 */
function* getFiles(fileDir: string) {
    const todoFileDirs: string[] = [fileDir];
    while (todoFileDirs.length > 0) {
        const currentFileDir = todoFileDirs.pop();
        if (!currentFileDir) throw new Error(`!currentFileDir`);
        const fileNames = fs.readdirSync(currentFileDir);
        for (let fileName of fileNames) {
            const filePath = path.join(currentFileDir, fileName);
            const stat = fs.statSync(filePath);
            if (stat.isFile()) {
                yield filePath;
            } else if (stat.isDirectory()) {
                todoFileDirs.push(filePath);
            }
        }
    }
}

function dtsReplace(fileDir: string) {
    for (let filePath of getFiles(fileDir)) {
        if (!filePath.endsWith('.d.ts')) continue;
        const text = fs.readFileSync(filePath, { encoding: 'utf-8', flag: 'r' });
        const replaceMap: [RegExp, string][] = [
            // ...libNames.map(e => [new RegExp(`@/${e}`, 'g'), sdkName] as [RegExp, string]),
            ...libNames.map(e => [new RegExp(`@/${e}`, 'g'), `${sdkName}/dist/types/${e}`] as [RegExp, string]),
        ];
        let text2 = text;
        for (let [r0, r1] of replaceMap) {
            text2 = text2.replace(r0, r1);
        }
        if (text !== text2) {
            fs.writeFileSync(filePath, text2, { encoding: 'utf-8' });
        }
    }
}

function processCommand() {
    const argv = yargs.option('i', {
        alias: 'input',
        demandOption: true,
        describe: '输入文件路径',
        type: 'string'
    }).parse(process.argv);
    const inputFileDir = argv.i;
    try {
        dtsReplace(inputFileDir);
    } catch (error) {
        console.error(`dtsReplace 发生错误error: ${error}`);
    }
}
processCommand();
